const Joi = require('joi');
const jwt = require('koa-jwt');
const HttpStatus = require('http-status-codes');

const { crasheyeUserModel } = require('./user.model');
const UserValidation = require('./user.validation');
const config = require('../../config/environment');


function* login() {
  const credentials = this.request.body;

  const validateResult = Joi.validate(credentials, UserValidation.loginSchema);
  if (validateResult.error) {
    this.throw(HttpStatus.BAD_REQUEST, validateResult.error.details[0].message);
  }

  let user = null;
  try {
    user = yield crasheyeUserModel.login(credentials.email, credentials.password);
  } catch (e) {
    this.throw(HttpStatus.BAD_REQUEST, e.message);
  }

  user = user.toJSON();
  const payload = { sub: user.id };
  const token = jwt.sign(payload, config.app.secret, { expiresIn: config.app.expires });
  this.state.user = user;
  this.body = { token };
}

const userController = {
  login,
};
module.exports = userController;


